import 'package:flutter/material.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:flutter_smart_heating/common/http.dart';
import 'package:flutter_smart_heating/mode/list_pagination_model.dart';
import 'package:flutter_smart_heating/ui/src/pull_to_refresh.dart';
import 'package:flutter_smart_heating/ui/ui.dart';

class InformationWeatherPage extends StatefulWidget {
  const InformationWeatherPage({super.key});

  @override
  State<InformationWeatherPage> createState() => _InformationWeatherPageState();
}

class _InformationWeatherPageState extends State<InformationWeatherPage> {
  List<dynamic> list = List.filled(15, {}).toList();
  ListPaginationModel pagination = ListPaginationModel();
  RefreshController refreshController = RefreshController();
  String keyword = '';
  fetchData() async {
    setState(() {});
    var res = await Http.instance.post(
      '/api/information/weather/index',
      data: {
        "page": pagination.currentPage,
        "keyword": keyword,
      },
    );

    if (res.code == 1) {
      if (pagination.currentPage <= 1) {
        list.clear();
      }
      pagination = ListPaginationModel.fromJson(res.data);
      res.data['data'].forEach(
        (item) => list.add(item),
      );
    }
    setState(() {});
    refreshController.refreshCompleted();
    if (pagination.hasMore) {
      refreshController.loadComplete();
    } else {
      refreshController.loadNoData();
    }
  }

  @override
  Widget build(BuildContext context) {
    Ui.onPageAnimateCompleted(context, fetchData);

    return Scaffold(
      appBar: AppBar(
        backgroundColor: UiTheme.of(context).match(light: Colors.white),
        scrolledUnderElevation: 0,
        title: const Text('历史天气'),
        actions: const [
          UiRightMenuButtonGroup(),
        ],
      ),
      body: KeyboardDismissOnTap(
        dismissOnCapturedTaps: true,
        child: Column(
          children: [
            Container(
              color: UiTheme.of(context).match(
                light: Colors.white,
                dark: Theme.of(context).appBarTheme.backgroundColor,
              ),
              padding: const EdgeInsets.only(
                top: UiTheme.toolbarSpacing,
                left: UiTheme.spacingX,
                right: UiTheme.spacingX,
                bottom: UiTheme.spacingX,
              ),
              alignment: Alignment.centerLeft,
              child: UiSearchBar(
                backgroundColor:
                    UiTheme.of(context).match(light: Colors.grey[100]),
                onSubmitted: (val) {
                  keyword = val;
                  pagination.currentPage = 1;
                  fetchData();
                },
                onClear: () {
                  keyword = '';
                  pagination.currentPage = 1;
                  fetchData();
                },
              ),
            ),
            const Divider(height: 0),
            Expanded(
              child: UiPushToRefresh(
                controller: refreshController,
                onRefresh: () {
                  pagination.currentPage = 1;
                  fetchData();
                },
                enablePullUp:
                    pagination.lastPage > 1 && !refreshController.isRefresh,
                onLoad: () {
                  pagination.currentPage++;
                  fetchData();
                },
                child: list.isEmpty
                    ? const Center(
                        child: UiResult(),
                      )
                    : ListView.separated(
                        separatorBuilder: (context, index) => const SizedBox(
                          height: UiTheme.spacingX,
                        ),
                        itemBuilder: (context, index) {
                          var item = list[index];
                          return itemView(item, index);
                        },
                        itemCount: list.length,
                      ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  UiOpen itemView(item, index) {
    bool isBlock = item['id'] == null;
    return UiOpen(
      url: item['url'] ?? '',
      child: UiPanel(
        height: 80,
        margin: EdgeInsets.only(
          top: index == 0 ? UiTheme.spacingX : 0,
          left: UiTheme.spacingX,
          right: UiTheme.spacingX,
          bottom: index == list.length - 1 ? 30 : 0,
        ),
        padding: const EdgeInsets.only(left: 15),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            ClipRRect(
              borderRadius: BorderRadius.circular(6),
              child: SizedBox(
                width: 50,
                child: UiImage(
                  imageUrl: item['icon'] ?? '',
                  fit: BoxFit.cover,
                ),
              ),
            ),
            const SizedBox(width: 15),
            Expanded(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  isBlock
                      ? const UiBlock(height: 20)
                      : Text(
                          item['date'] ?? '',
                          overflow: TextOverflow.ellipsis,
                          style: const TextStyle(
                            fontWeight: FontWeight.w500,
                            fontSize: 16,
                          ),
                        ),
                  const SizedBox(height: 5),
                  isBlock
                      ? const UiBlock(height: 20)
                      : Opacity(
                          opacity: 0.8,
                          child: Text(
                            item['text'] ?? '',
                            textAlign: TextAlign.center,
                            overflow: TextOverflow.ellipsis,
                            textScaler: const TextScaler.linear(0.95),
                          ),
                        ),
                ],
              ),
            ),
            const SizedBox(width: UiTheme.spacingX),
            SizedBox(
              width: 70,
              child: isBlock
                  ? const UiBlock(height: 20)
                  : Column(
                      mainAxisSize: MainAxisSize.min,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          children: [
                            const Text(
                              '最高',
                              style: TextStyle(fontSize: 12),
                            ),
                            const SizedBox(width: 5),
                            Text(
                              '${item['high']}°',
                              style:
                                  const TextStyle(fontWeight: FontWeight.bold),
                            ),
                          ],
                        ),
                        const SizedBox(height: 3),
                        Row(
                          children: [
                            const Text(
                              '最低',
                              style: TextStyle(fontSize: 12),
                            ),
                            const SizedBox(width: 5),
                            Text(
                              '${item['low']}°',
                              style:
                                  const TextStyle(fontWeight: FontWeight.bold),
                            ),
                          ],
                        ),
                      ],
                    ),
            ),
          ],
        ),
      ),
    );
  }
}
